package com.juggernaut;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CurtorTest {

    public static void main(String[] args) throws Exception {
        // 创建zookeeper的客户端
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);
        client.start();
        CountDownLatch cd = new CountDownLatch(2);
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        newCachedThreadPool.execute(() -> {
            // 创建分布式锁, 锁空间的根节点路径为/curator/lock
            InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
            try {
                System.out.println(String.format("%s正在获取锁", Thread.currentThread().getName()));
                mutex.acquire();
                // 获得了锁, 进行业务流程
                System.out.println("Enter mutex1");

                TimeUnit.SECONDS.sleep(10);

                // 完成业务流程, 释放锁
                mutex.release();

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                cd.countDown();
            }

        });

        newCachedThreadPool.execute(() -> {
            // 创建分布式锁, 锁空间的根节点路径为/curator/lock
            InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
            try {
                System.out.println(String.format("%s正在获取锁", Thread.currentThread().getName()));
                mutex.acquire();
                // 获得了锁, 进行业务流程
                System.out.println("Enter mutex2");

                TimeUnit.SECONDS.sleep(100);

                // 完成业务流程, 释放锁
                mutex.release();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                cd.countDown();
            }

        });

        cd.await();

        // 关闭客户端
        client.close();
    }
}
